from pathlib import Path

import pandas as pd
import numpy as np
import warnings

warnings.filterwarnings('ignore')
from StressAna.Lib.Utils import DateTimeUtil


class AnkeAna():
    def __init__(self, file):
        self.srcFile = file
        self._data = {}
        self._raw_df = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self._init()

    @property
    def df(self):
        return self._raw_df

    @property
    def data(self):
        if not self._data:
            df = self._raw_df
            df['date'] = df['time'].apply(
                lambda x: DateTimeUtil.formatDateTimeBy(DateTimeUtil.parseDateTimeBy(x, "%Y-%m-%d %H:%M:%S"),
                                                        "%Y-%m-%d"))
            df['timestamp'] = df['time'].apply(
                lambda x: DateTimeUtil.formatTimeStamp(DateTimeUtil.parseDateTimeBy(x, "%Y-%m-%d %H:%M:%S")))
            self._data['sID'] = df.iloc[0, 0]
            for date, dfi in df.groupby('date'):
                srcData = np.zeros([3, len(dfi)], dtype='float')
                start_stamp = DateTimeUtil.formatTimeStamp(
                    DateTimeUtil.parseDateTimeBy(f"{date} 00:00:00", "%Y-%m-%d %H:%M:%S"))
                dataLen = 0
                for index, row_data in dfi.iterrows():
                    x = row_data['timestamp'] - start_stamp
                    srcData[0][dataLen] = x
                    srcData[1][dataLen] = row_data['ch1']
                    srcData[2][dataLen] = row_data['ch2']
                    dataLen += 1
                self._data[date] = srcData
        return self._data

    def _init(self):
        if Path(self.srcFile).name != 'out_morning.xlsx':
            try:
                _df = pd.DataFrame(columns=['传感器编号', '时间', '通道1', '通道2'])
                _raw_dict = pd.read_excel(self.srcFile, sheet_name=None,
                                          usecols=['传感器编号', '时间', '通道1', '通道2'],
                                          dtype={'时间': 'datetime64[ns]', '传感器编号': 'str'})
                for key, item in _raw_dict.items():
                    _df = _df._append(item)
                _df.rename(columns={'传感器编号': 'sID', '时间': 'time', '通道1': 'ch1', '通道2': 'ch2'},
                           inplace=True)
                self._raw_df = self._raw_df._append(_df)
            except ValueError:
                _df = pd.DataFrame(columns=['传感器编号', '时间', '通道1-监测值', '通道2-监测值'])
                try:
                    _raw_dict = pd.read_excel(self.srcFile, sheet_name=None,
                                              usecols=['传感器编号', '时间', '通道1-监测值', '通道2-监测值'],
                                              dtype={'时间': 'datetime64[ns]', '传感器编号': 'str'})
                except ValueError:
                    return
                for key, item in _raw_dict.items():
                    _df = _df._append(item)
                _df.rename(columns={'传感器编号': 'sID', '时间': 'time', '通道1-监测值': 'ch1', '通道2-监测值': 'ch2'},
                           inplace=True)
                self._raw_df = self._raw_df._append(_df)
        elif Path(self.srcFile).name == 'out_morning.xlsx':
            _raw_df = pd.read_excel(self.srcFile, dtype={'日期时间': 'datetime64[ns]'})
            df_1 = _raw_df[(_raw_df['测点名称'].str.contains('浅'))]
            df_1 = df_1.rename(columns={'测点名称': '传感器编号', "应力": "通道1-监测值", '日期时间': '时间'})
            df_1.loc[:, '传感器编号'] = df_1['传感器编号'].apply(lambda x: x[:-3])
            df_2 = _raw_df[(_raw_df['测点名称'].str.contains('深'))]
            df_2 = df_2.rename(columns={'测点名称': '传感器编号', "应力": "通道2-监测值", '日期时间': '时间'})
            df_2.loc[:, '传感器编号'] = df_2['传感器编号'].apply(lambda x: x[:-3])
            self._raw_df = pd.merge(df_1, df_2, how='outer')
            self._raw_df.rename(
                columns={'传感器编号': 'sID', '时间': 'time', '通道1-监测值': 'ch1', '通道2-监测值': 'ch2'},
                inplace=True)


if __name__ == '__main__':
    ana = AnkeAna(r'../Data/钻孔应力传感器-10-_20240125143622.xlsx')
    print(ana.df)
